package org.breathe.dynamic.thread.pool.core.handler;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.breathe.dynamic.thread.pool.core.parser.ConfigParser;
import org.breathe.thread.pool.common.enums.ConfigFileTypeEnum;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * 配置处理
 * @author: breathe
 * @createTime: 2025-04-13
 */
@Slf4j
public class ConfigHandler {
    private static final List<ConfigParser> PARSERS = Lists.newArrayList();

    public ConfigHandler() {
        //支持spi机制
        ServiceLoader.load(ConfigParser.class).forEach(PARSERS::add);
        log.info("PARSERS: {}", PARSERS);
    }
    public Map<Object, Object> parseConfig(String content, ConfigFileTypeEnum type) throws IOException {
        for (ConfigParser parser : PARSERS) {
            if (parser.supports(type)) {
                return parser.doParse(content);
            }
        }
        return Collections.emptyMap();
    }

    public static ConfigHandler getInstance() {
        return ConfigHandlerHolder.INSTANCE;
    }
    private static class ConfigHandlerHolder {
        private static final ConfigHandler INSTANCE = new ConfigHandler();
    }
}
